package MultiThread;

import java.util.concurrent.BrokenBarrierException;
import java.util.concurrent.CyclicBarrier;

public class CyclicBarrierTest {

    private static CyclicBarrier cyclicBarrier = new CyclicBarrier(10);

    public static void main(String[] args) {
        for (int i = 0; i < 10; i++) {
            new Thread(new Worker2(cyclicBarrier, i)).start();
        }
    }
}


class Worker2 implements Runnable{

    private CyclicBarrier cyclicBarrier;

    private int i;

    public Worker2(CyclicBarrier c, int i) {
        this.cyclicBarrier = c;
        this.i = i;
    }

    @Override
    public void run() {
        try {
            System.out.println(String.format("第%s个线程，第1次循环", i));
            cyclicBarrier.await();

            System.out.println(String.format("第%s个线程，第2次循环", i));
            cyclicBarrier.await();

            System.out.println(String.format("第%s个线程，第3次循环", i));
            cyclicBarrier.await();
        } catch (InterruptedException e) {
            e.printStackTrace();
        } catch (BrokenBarrierException e) {
            e.printStackTrace();
        }

    }
}
